<template>
  <el-dialog
    :title="title"
    v-model="open"
    width="80%"
    top="5vh"
    append-to-body
    draggable
  >
    <el-tabs v-model="activeName" tab-position="left">
      <el-tab-pane
        v-for="(value, key) in data"
        :key="key"
        :label="value.template.templateName"
        :name="key"
      >
        <div class="content">
          <el-button
            link
            icon="DocumentCopy"
            @click="handleCopy(value.content)"
            style="padding: 10px 10px; margin-left: auto"
            >复制代码</el-button
          >
          <div class="code-wrapper">
            <codemirror
              v-model="value.content"
              :style="{ height: '100%' }"
              autofocus
              indent-with-tab
              :tabSize="4"
              :extensions="getExtensions(value.language)"
              readOnly
            />
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </el-dialog>
</template>

<script setup>
import { Codemirror } from "vue-codemirror";
import { oneDark } from "@codemirror/theme-one-dark";
import { useClipboard } from "@vueuse/core";
import { csharp } from "@replit/codemirror-lang-csharp";
import { vue } from "@codemirror/lang-vue";
import { javascript } from "@codemirror/lang-javascript";

const { copy, isSupported } = useClipboard();
const { proxy } = getCurrentInstance();

// 根据语言类型返回对应的扩展配置
const getExtensions = (language) => {
  let langExtension;
  switch (language) {
    case "Vue":
      langExtension = vue();
      break;
    case "C#":
      langExtension = csharp();
      break;
    case "JavaScript":
      langExtension = javascript();
      break;
    default:
      // 默认使用 JavaScript 高亮
      langExtension = javascript();
  }
  return [langExtension, oneDark];
};

const open = defineModel({
  type: Boolean,
  default: false,
});

const data = defineModel("data", {
  type: Array,
  default: [],
});
const title = ref("代码预览");
const activeName = ref(0);

const handleCopy = async (content) => {
  if (!isSupported) {
    proxy.$modal.msgError("浏览器不支持剪贴板操作");
    return;
  }
  try {
    await copy(content);
    proxy.$modal.msgSuccess("复制成功");
  } catch {
    proxy.$modal.msgError("复制失败");
  }
};
</script>

<style scoped>
.content {
  height: 80vh;
  display: flex;
  flex-direction: column;
}

.code-wrapper {
  flex: 1;
  overflow: hidden;
}
</style>
